package be.scond.cartpool;

import java.io.IOException;
import java.math.BigDecimal;

import javax.servlet.http.*;
import be.scond.cartpool.API.ShoppingListApi;
import be.scond.cartpool.exceptions.NoShoppingListFoundException;
import be.scond.cartpool.exceptions.UserNotFoundException;
import be.scond.cartpool.model.Order;

public class CreateOrderServlet extends HttpServlet {
	
	static final long serialVersionUID = 1;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/xml");
		
		String groupName = req.getParameter("groupName");
		String email = req.getParameter("email");		
		String product = req.getParameter("product");
		String description = req.getParameter("description");
		String listKey = null;
		listKey = req.getParameter("listKey");
		
		int quantity;
		BigDecimal price;

		try {
			price = BigDecimal.valueOf(Double.parseDouble(req.getParameter("price")));
		} catch (NumberFormatException e) {
			price = BigDecimal.valueOf(Double.NaN);
		}
		
		String respons = "<data>";	
		if(product.length() < 3){
			respons += "<error>product description cannot be empty</error>";
		}else{
			try {
				quantity = Integer.parseInt(req.getParameter("quantity"));
				
				Order order = null;
				if(listKey == null){
					order = ShoppingListApi.createOrder(email, groupName, product, quantity, price, description);	
					respons += "<succes>Order created.</succes>";			
				}else{
					order = ShoppingListApi.createOrderOnOldShoppingList(email, groupName, product, quantity, price, listKey, description);
					respons += "<succes>Order created.</succes>";			
				}
				
				
				respons += order.toXmlString();
				
			} catch (NumberFormatException e) {
				respons += "<error>quantity was not a valid number</error>";
			} catch (UserNotFoundException e) {
				respons += "<error>User was not found</error>";
			} catch (NoShoppingListFoundException e) {
				respons += "<error>No ShoppingList could be found</error>";	
			}	
		}
		
		respons += "</data>";

		resp.getWriter().print(respons);
	}
}